package com.lagou.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;
import java.util.Date;

/**
 * 按时间分表的自定义分片算法
 */
public class TimeShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
        Date createTime = shardingValue.getValue();
        if (createTime == null) {
            throw new IllegalArgumentException("create_time cannot be null");
        }
        
        // 格式化时间为 yyyyMM 格式
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMM");
        String timeStr = sdf.format(createTime);
        
        // 构建表名：b_order + yyyyMM
        String tableName = "b_order" + timeStr;
        
        System.out.println("=== TimeShardingAlgorithm Debug Info ===");
        System.out.println("Input createTime: " + createTime);
        System.out.println("Formatted timeStr: " + timeStr);
        System.out.println("Generated tableName: " + tableName);
        System.out.println("Available target names: " + availableTargetNames);
        
        // 检查目标表名是否在可用表名集合中
        if (availableTargetNames.contains(tableName)) {
            System.out.println("Found target table: " + tableName);
            return tableName;
        }
        
        // 如果目标表不存在，返回第一个可用的表名
        // 这里可以根据实际需要调整策略，比如创建表或者使用默认表
        String defaultTable = availableTargetNames.iterator().next();
        System.out.println("Table " + tableName + " not found, using default table: " + defaultTable);
        System.out.println("=== End Debug Info ===");
        return defaultTable;
    }
} 